var jgd = {
    setBtnStatus: function () {
        var row = $('#jgd-grid').datagrid('getSelected');
        if (row && row.id && row.zt) {
            if (row.zt == 0) {
                $("#btn_jgd_mod").show();
                $("#btn_jgd_del").show();
                $("#btn_jgd_confirm").show();
            } else if (row.zt == 1 || row.zt == 2) {
                $("#btn_jgd_mod").hide();
                $("#btn_jgd_del").hide();
                $("#btn_jgd_confirm").hide();
            }
        } else {
            $("#btn_jgd_mod").hide();
            $("#btn_jgd_del").hide();
            $("#btn_jgd_confirm").hide();
        }
    },
    alwayShowDetail: function (rowData) {
        $('#layout_jgd').layout('remove', 'center');
        $('#layout_jgd').layout('add', {
            region: 'center',
            split: true,
            href: $.webPath() + '/jggl/jgdgl/jgd_detail?jgdId=' + rowData.id
        });
    },
    showDetail: function (rowData) {
        if (rowData && $("#jgd_detail_id").val() != rowData.id) {
            jgd.alwayShowDetail(rowData);
        }
    }


}
$(function () {
    //表格初始加载
    $('#jgd-grid').datagrid({
        url: $.webPath() + "/jggl/jgdgl/jgdList",
        toolbar: "#jgd-toolbar",
        fitColumns: true,
        singleSelect: true,
        pagination: true,
        pageNumber: 1,
        remoteSort: false,
        showFooter: true,
        fit: true,
        rownumbers: true,
        striped: true,
        columns: [
            [
                {field: 'id', title: 'ID', hidden: true},
                {field: 'jgdh', title: '加工单号', align: 'center', width: 113, formatter: jgdCell, sortable: 'true'},
                {field: 'jgrq', title: '加工日期', align: 'center', width: 100, sortable: 'true'},
                {field: 'sqgs_jc', title: '申请公司', align: 'center', width: 78},
                {field: 'sbgs_jc', title: '申报公司', align: 'center', width: 78},
                {field: 'sbr_xm', title: '申报人', align: 'center', width: 78},
                {field: 'sbrq', title: '申报日期', align: 'center', width: 100, sortable: 'true'},
                {field: 'rate', title: '预期成材料率', align: 'center', width: 65,
                    formatter: function (value) {
                        if (null != value && value >= 0)
                            return value + '%';
                    }
                },
                {field: 'sjrate', title: '实际成材料率', align: 'center', width: 65,
                    formatter: function (value) {
                        if (null != value && value >= 0)
                            return value + '%';
                    }
                },
                {field: 'jgzl', title: '加工调出计量', align: 'center', width: 65,
                    formatter: function (value) {
                        if (value && value > 0) {
                            return value.toFixed(4);
                        } else {
                            return 0;
                        }
                    }
                },
                {field: 'jghzl', title: '加工调入计量', align: 'center', width: 65,
                    formatter: function (value) {
                        if (value && value > 0) {
                            return value.toFixed(4);
                        } else {
                            return 0;
                        }
                    }},
                {field: "zt", title: "状态", align: 'center', width: 47,
                    formatter: function (value) {
                        if (value == '0')
                            return '已保存';
                        if (value == '1')
                            return '已提交';
                        if (value == '2')
                            return '已完结';
                    }, sortable: 'true'
                }
            ]
        ],
        onLoadSuccess: function () {
            $(this).datagrid('selectRow', 0);
            jgd.setBtnStatus();
            $(".datagrid-htable .datagrid-cell").css('text-align', 'center');
        },
        onClickRow: function () {
            jgd.setBtnStatus();
        },
        onSelect: function (rowIndex, rowData) {
            jgd.setBtnStatus();
        }
    });

    //  改变背景色
    $('#jgd-grid').datagrid({
        rowStyler: function (index, row) {
            if (row.zt == 2) {
                return 'background-color:#7EC0EE';
            } else {
                if (row.jgzl && row.jgzl > 0) {
                    return 'background-color:yellow';
                }
            }
        }
    });
    //**********按钮触发事件**********
    /*******************新增加工单*****************************************/
    var jgd_win;
    var actionUrl;
    var isEdit;
    $("#btn_jgd_add").click(function () {
        var tit = "新增加工单";
        var button = [
            {text: '确认', handler: jgd_add}
        ];
        jgd_win = $.window({
            title: tit,
            iconCls: 'icon-add2',
            url: $.webPath() + "/jggl/jgdgl/jgd_into",
            buttons: button,
            width: 1000,
            height: 500,
            maximizable: true,
            model: true
        });
    });
    // 保存
    function jgd_add() {
        var data = $('#search-jgd-selected-jgd-grid').datagrid("getData");
        var arr = new Array();
        if (data.rows.length <= 0) {
            $.messager.alert('提示', "请选择库存信息！", 'info');
            return;
        } else {
            $.each(data.rows, function (i, val) {
                arr[i] = data.rows[i];
            })
        }
        var jsonText = JSON.stringify(arr);
        $.ajax({
            url: $.webPath() + "/jggl/jgdgl/jgd_add",
            type: "post",
            dataType: 'text',
            data: {jsonText: jsonText},
            success: function (data) {
                var obj = eval('(' + data + ')');
                if (obj.statusCode == '200') {
                    $(jgd_win).window('close');
                    $('#jgd-grid').datagrid('reload');
                    $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                    var href = $.webPath() + "/jggl/jgdgl/jgd_content?jgdId=" + obj.jgdId
                    actionUrl = $.webPath() + "/jggl/jgdgl/update_jgd";
                    jgd_editShowDialog("添加加工单", href);
                } else {
                    $(jgd_win).window('close');
                    $('#jgd-grid').datagrid('reload');
                    $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                }
            },
            error: function (data) {
                alert(data);
            }
        });
    }

    /*******************修改加工单*****************************************/
    $("#btn_jgd_mod").click(function () {
        var record = $("#jgd-grid").datagrid("getSelected");
        if (record == null) {
            $.messager.alert("提示", "请选择要修改的加工单!", "warning");
            return;
        }
        var href = $.webPath() + "/jggl/jgdgl/jgd_content?jgdId=" + record.id;
        actionUrl = $.webPath() + "/jggl/jgdgl/update_jgd";
        isEdit = "yes";
        jgd_editShowDialog("修改加工单", href);
    });

    function jgd_editShowDialog(title, href) {
        var button
        button = [
            {text: '保存', handler: jgd_saveItem}
        ];
        jgd_win = $.window({
            title: title,
            iconCls: 'icon-add2',
            url: href,
            width: 1024,
            height: 500,
            buttons: button
        });
    }

    function jgd_saveItem() {

        // 必输入判断
        var isValid = $('#jgdglForm').form('validate');
        if (!isValid) {
            return isValid;
        }

        // 明细判断
        $("#jgd_mx").edatagrid('saveRow');
        $('#jgdglForm').tabs('select', "加工单明细");
        var data = $('#jgd_mx').edatagrid("getData");
        var arr = new Array();
        var yqccArr = new Array();
        if (!data.rows.length) {
            $(jgd_win).mask('hide');
            $('#jgdglForm').tabs('select', "加工单明细");
            $.messager.alert("提示", "请填写加工单明细!", "waring");
            return false;
        }
        for (var i = 0; i < data.rows.length; i++) {
            //验证每行记录的合法性
            if (data.rows[i].sbsl == 0 || !data.rows[i].sbsl) {
                $('#jgdglForm').tabs('select', "加工单明细");
                $.messager.alert('提示', '第' + (i + 1) + '行的数量不能为0或者为空 !', 'info');
                return false;
            } else if (data.rows[i].sbsl == 0 || !data.rows[i].sbsl) {
                $('#jgdglForm').tabs('select', "加工单明细");
                $.messager.alert('提示', '第' + (i + 1) + '行的计量不能为0或者为空 !', 'info');
                return false;
            }
            arr[i] = data.rows[i];
        }
        $("#yqcc_mx_edatagrid").edatagrid('saveRow');
        var yqccdata = $('#yqcc_mx_edatagrid').edatagrid("getData");
        for (var i = 0; i < yqccdata.rows.length ; i++) {
            //验证每行记录的合法性
            if (yqccdata.rows[i].wzggCode) {
                if (!yqccdata.rows[i].cdId) {
                    $('#jgdglForm').tabs('select', "预期成材明细");
                    $.messager.alert('提示', '第' + (i + 1) + '行的产地为空 !', 'info');
                    return false;
                } else if ( !yqccdata.rows[i].ccsl || yqccdata.rows[i].ccsl == 0 ) {
                    $('#jgdglForm').tabs('select', "预期成材明细");
                    $.messager.alert('提示', '第' + (i + 1) + '行的数量不能为0或者为空 !', 'info');
                    return false;
                } else if (!yqccdata.rows[i].cczl || yqccdata.rows[i].cczl == 0) {
                    $('#jgdglForm').tabs('select', "预期成材明细");
                    $.messager.alert('提示', '第' + (i + 1) + '行的计量不能为0或者为空 !', 'info');
                    return false;
                }
                yqccArr[i] = yqccdata.rows[i];
            }
        }
        var jsonText = JSON.stringify(arr);
        var jsonText1 = JSON.stringify(yqccArr);
        $.ajax({
            url: actionUrl,
            type: "post",
            dataType: 'text',
            data: {jsonText: jsonText, jsonText1: jsonText1, rate: $("#jgd_rate_id").val(), bz: document.getElementById("jgd_bz_id").value},
            success: function (data) {
                var obj = eval('(' + data + ')');
                if (obj.statusCode == '200') {
                    $(jgd_win).window('close');
                    $('#jgd-grid').datagrid('reload');
                    $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                } else {
                    $(jgd_win).window('close');
                    $('#jgd-grid').datagrid('reload');
                    $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                }
            },
            error: function (data) {
                alert(data);
            }
        });
    }

    //删除按钮
    $("#btn_jgd_del").click(function () {
        jgd_delete();
    });
    //审核按钮
    $("#btn_jgd_confirm").click(function () {
        jgd_check();
    });
    //查询按钮
    $("#btn_jgd_search").click(function () {
        jgd_search();
    });
    //双击事件
    $("#jgd-grid").datagrid({
        onDblClickCell: function (index, field) {
            if (field == "jsdh") {
                $("#btn_jgd_mod:visible").click();
            }
        }
    });
    //加载查询条件中的申报公司
    $("[name='jgd_sqgs']").qyjgzcombobox();

    //加载查询条件中的申报公司下拉框
    $("[name='jgd_sbgs']").jgbmtree($("[name='jgd_sbbm']"), $("[name='jgd_sbr']"), '', '')
});

//删除加工单
function jgd_delete() {
    var row = $('#jgd-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('提示', '是否删除该加工单？', function (r) {
            if (r) {
                var index = $('#jgd-grid').datagrid('getRowIndex', row);
                $.ajax({
                    url: $.webPath() + "/jggl/jgdgl/delete_jgd",
                    dataType: 'json',
                    type: 'POST',
                    data: {jgdId: row.id},
                    beforeSend: function () {
                        $("#layout_jgd").mask();
                    },
                    success: function (data) {
                        $("#layout_jgd").mask("hide");
                        if (data.statusCode == 200) {
                            $('#jgd-grid').datagrid('deleteRow', index);
                            $.messager.show({
                                title: '提示',
                                msg: data.message,
                                timeout: 3000,
                                showType: 'slide'
                            });
                        } else {
                            $.messager.alert("提示", data.message, "error");
                        }
                    }
                });
            }
        });
    } else {
        $.messager.alert("提示", "请选择要删除的加工单！", "warning");
    }
}

//审核
function jgd_check() {
    var row = $('#jgd-grid').datagrid('getSelected');
    if (row) {
        if (!row.rate) {
            $.messager.alert("提示", "预期成材料率不能为空，请修改！", "warning");
        } else {
            $.messager.confirm('提示', '是否对该加工单进行审核？该加工单申报总重量为：' + row.sumsbzl + '立方米(m³)，' + '预期成材率为：' + row.rate + '%。', function (r) {
                if (r) {
                    $.ajax({
                        url: $.webPath() + "/jggl/jgdgl/change_status",
                        type: "post",
                        dataType: 'text',
                        data: {jgdId: row.id, zt: 1},
                        success: function (data) {
                            var obj = eval('(' + data + ')');
                            if (obj.statusCode == '200') {
                                $('#jgd-grid').datagrid('reload');
                                $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                            } else {
                                $('#jgd-grid').datagrid('reload');
                                $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                            }
                        },
                        error: function (data) {
                            alert(data);
                        }
                    });
                }
            });
        }
    } else {
        $.messager.alert("提示", "请选择要审核的加工单！", "warning");
    }
}

//加工单查询
function jgd_search() {
    var jgdh = $("#jgd-toolbar input[name='jgd_jgdh']").val();
    var sqrqStart = $('#sqrq_start').datebox('getValue');
    var sqrqEnd = $('#sqrq_end').datebox('getValue');
    var sqgsId = $("#jgd-toolbar input[name='jgd_sqgs']").val();
    var sbgsId = $("#jgd-toolbar input[name='jgd_sbgs']").val();
    var zt = $("#jgd-toolbar input[name='jgd_zt']").val();
    $('#jgd-grid').datagrid('load',
        {
            jgdh: jgdh,
            sqrqStart: sqrqStart,
            sqrqEnd: sqrqEnd,
            sqgsId: sqgsId,
            sbgsId: sbgsId,
            zt: zt
        }
    );
}
